using System;
using System.Web.UI.WebControls;
using Sedna.Core.Controller;
using Sedna.Core.Controller.Configurations;

namespace Sedna.Core.Controls.Grid
{
    public class GridCheckBox : CheckBox, IDataGridAwareControl
	{
		private int entityIndex;
		private IDataGridController controller;
        private IGridCheckBoxConfiguration configuration;

		public IDataGridController Controller
		{
			set { controller = value; }
		}

        new public IGridCheckBoxConfiguration Configuration
        {
            get { return configuration; }
            set { this.configuration = value; }
        }


		public GridCheckBox(IConfiguration configuration) : base(configuration)
		{
		    this.configuration = (IGridCheckBoxConfiguration) configuration;
			this.CheckedChanged+=new EventHandler(OnCheckedChanged);
		}

		private void OnCheckedChanged(object sender, EventArgs e)
		{
            this.entityIndex = (int)ViewState["entityIndex"];

            if (controller.GridSourceCache != null)
            {
                UpdateEntity();
                if (Configuration.IsDataGridMarker)
                {
                    MarkEntity();
                }
            }
		}

		private void UpdateEntity()
		{            
			object entity=this.controller.GridSourceCache[entityIndex];
			if (binder.Unbind(entity, "Checked"))
			{
				controller.TransientData.Add(entity);
			}
		}

		private void MarkEntity()
		{
			object entity=this.controller.GridSourceCache[entityIndex];
			if (Checked)
			{
				controller.MarkedData.Add(entity);
			}
			else
			{
				controller.MarkedData.Remove(entity);
			}
		}

		public void OnDataBinding(DataGridItem dataGridItem)
		{
			this.entityIndex = dataGridItem.DataSetIndex;
            ViewState["entityIndex"] = this.entityIndex;
			binder.Bind(dataGridItem.DataItem, new string[]{"Checked", "Text", "TextKey", "Enabled"});
		    if (Configuration.IsDataGridMarker && Configuration.LeaveTicks)
		    {
                Checked = (controller.MarkedData.Contains(dataGridItem.DataItem));
		    }
		}



		protected override void Bind() 
		{
		}

		protected override void Unbind()
		{
		}
	}
}
